import { HttpErrorResponse, HttpEvent, HttpHandler, HttpHeaderResponse, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
import { AppService } from './app.service';
import { Consts } from '../models/consts/consts';

@Injectable({
  providedIn: 'root'
})
export class ResponseInterceptorService implements HttpInterceptor {

  constructor(private _appService: AppService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      map((event) => {
        if (event instanceof HttpHeaderResponse ) {
          console.log('resp HttpHeaderResponse');
        } else if (event instanceof HttpErrorResponse) {
          console.log('resp HttpErrorResponse'); 
        } else if (event instanceof HttpResponse) {
          console.log('resp HttpResponse');
        } else {
          console.log('resp unknonw event type');
        }
        if (event instanceof HttpResponse && (event.status == Consts.UNAUTHORIZED || event.status == Consts.BAD_REQUEST)) {
          console.log(`intercept response with ${event.status}`);
          this._appService.logout();
        }
        return event;
      })
    )
  }
}
